package qc.module.ehs.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import qc.common.core.enums.EhsTaskCategoryTypeEnum;
import qc.common.core.enums.EhsTaskDestObjectTypeEnum;
import qc.common.core.enums.EhsTaskGroupObjectTypeEnum;
import qc.common.core.enums.TimeRangeLengthEnum;
import qc.common.core.exception.QCPromptException;
import qc.common.core.unify.QCUnifyReturnValue;
import qc.common.core.utils.DateUtil;
import qc.common.core.utils.IdentifierUtil;
import qc.module.ehs.dto.hazard.EhsHazardInfoDto;
import qc.module.ehs.dto.troublecorrect.*;
import qc.module.ehs.entity.EhsTaskGroup;
import qc.module.ehs.entity.EhsTaskInfo;
import qc.module.ehs.entity.EhsTaskItem;
import qc.module.ehs.entity.EhsTroubleCorrect;
import qc.module.ehs.mapper.EhsTroubleCorrectMapper;
import qc.module.ehs.repository.EhsTaskGroupRepository;
import qc.module.ehs.repository.EhsTaskInfoRepository;
import qc.module.ehs.repository.EhsTaskItemRepository;
import qc.module.ehs.repository.EhsTroubleCorrectRepository;
import qc.module.platform.dto.uac.UacUserInfoDto;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 隐患治理Service
 * @author QuCheng Tech
 * @since 2024/11/7
 */
@Service
public class EhsTroubleCorrectService {

    @Autowired
    private EhsTroubleCorrectRepository repository;

    @Autowired
    private EhsTaskInfoRepository taskInfoRepository;

    @Autowired
    private EhsTaskGroupRepository taskGroupRepository;

    @Autowired
    private EhsTaskItemRepository taskItemRepository;

    @Autowired
    private EhsHazardInfoService hazardInfoService;

    /**
     * 查询隐患治理
     * @param condition 查询条件
     * @return List<EhsTroubleCorrectInfoDto>
     * @author QuCheng Tech
     * @since 2024/11/7
     */
    public List<EhsTroubleCorrectInfoDto> query(EhsTroubleCorrectQueryConditionDto condition) throws QCPromptException {
        //1.查询条件有效性验证
        if (condition == null)
            throw new QCPromptException("查询条件不能为空");
        if (StringUtils.isBlank(condition.getOrgcode()))
            throw new QCPromptException("组织代码不能为空");
        if (StringUtils.isBlank(condition.getBegintm()))
            throw new QCPromptException("起始时间不能为空");
        if (StringUtils.isBlank(condition.getEndtm()))
            throw new QCPromptException("截止时间不能为空");

        //查询时间处理
        Date beginDate = null;
        Date endDate = null;
        if (StringUtils.isNotBlank(condition.getBegintm())) {
            try {
                beginDate = DateUtil.parseDate(condition.getBegintm());
            } catch (Exception e) {
                // 时间转换错误，抛出自定义异常
                throw new QCPromptException("查询条件中的开始日期转换错误");
            }
        }
        if (StringUtils.isNotBlank(condition.getEndtm())) {
            try {
                endDate = DateUtil.parseDate(condition.getEndtm());
            } catch (Exception e) {
                // 时间转换错误，抛出自定义异常
                throw new QCPromptException("查询条件中的截止日期转换错误");
            }
        }

        //2.构建隐患治理查询条件
        LambdaQueryWrapper<EhsTroubleCorrect> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EhsTroubleCorrect::getOrgcode, condition.getOrgcode());
        Date finalBeginDate = beginDate;
        Date finalEndDate = endDate;
        wrapper.and(q -> {
            q.ge(EhsTroubleCorrect::getTm, finalBeginDate).le(EhsTroubleCorrect::getTm, finalEndDate);
        });
        if (StringUtils.isNotBlank(condition.getStatus())) {
            if (Integer.parseInt(condition.getStatus()) == 1) {
                //已验收通过
                wrapper.eq(EhsTroubleCorrect::getHascheck, true);
            } else if (Integer.parseInt(condition.getStatus()) == 2) {
                //已整改完成
                wrapper.eq(EhsTroubleCorrect::getHascorrect, true);
            } else if (Integer.parseInt(condition.getStatus()) == 3) {
                //已派单
                wrapper.eq(EhsTroubleCorrect::getHasdispatch, true);
            } else if (Integer.parseInt(condition.getStatus()) == 4) {
                //未派单
                wrapper.eq(EhsTroubleCorrect::getHasdispatch, false);
            }
        }
        if (StringUtils.isNotBlank(condition.getUnitid())) {
            wrapper.eq(EhsTroubleCorrect::getUnitid, condition.getUnitid());
        }
        if (StringUtils.isNotBlank(condition.getKeywords())) {
            wrapper.and(q -> q.like(EhsTroubleCorrect::getCategoryname, condition.getKeywords()).or()
                            .like(EhsTroubleCorrect::getProjectname, condition.getKeywords()).or()
                            .like(EhsTroubleCorrect::getItemname, condition.getKeywords())).or()
                    .like(EhsTroubleCorrect::getTitle, condition.getKeywords()).or()
                    .like(EhsTroubleCorrect::getPosition, condition.getKeywords()).or()
                    .like(EhsTroubleCorrect::getCouse, condition.getKeywords()).or()
                    .like(EhsTroubleCorrect::getMaycouseharm, condition.getKeywords()).or()
                    .like(EhsTroubleCorrect::getDescription, condition.getKeywords());
        }

        //3.查询隐患治理记录
        List<EhsTroubleCorrect> ens = repository.selectList(wrapper);
        if (CollectionUtils.isNotEmpty(ens)) {
            return EhsTroubleCorrectMapper.MAPPER.toDtoList(ens);
        }
        return null;
    }

    /**
     * 批量派单
     * <p>
     * 已派单隐患不再重复派单
     * 隐患派单后，新增一个任务，每个隐患新增为一个分组，新增任务项
     * @param dto 批量派单DTO
     * @return 成功返回null，失败返回错误或提示信息
     * @author QuCHeng Tech
     * @since 2024/11/19
     */
    public String batchDispatch(EhsTroubleCorrectBatchDispatchDto dto, UacUserInfoDto userInfo) throws QCPromptException {
        //1.DTO有效性验证
        if (dto == null)
            return QCUnifyReturnValue.Warn("派单信息不能为空");
        if (CollectionUtils.isEmpty(dto.getIds()))
            return QCUnifyReturnValue.Warn("隐患治理ID集合不能为空");
        if (StringUtils.isBlank(dto.getEndtm()))
            return QCUnifyReturnValue.Warn("整改时限不能为空");

        //整改时限时间处理
        Date endDate = null;
        if (StringUtils.isNotBlank(dto.getEndtm())) {
            try {
                endDate = DateUtil.parseDate(dto.getEndtm());
            } catch (Exception e) {
                // 时间转换错误，抛出自定义异常
                throw new QCPromptException("批量派单整改时限转换错误");
            }
        }

        List<EhsTroubleCorrect> ens = repository.selectBatchIds(dto.getIds());
        if (CollectionUtils.isNotEmpty(ens)) {
            List<EhsTroubleCorrect> dispatchEns = ens.stream().filter(p -> p.getHasdispatch()).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(dispatchEns))
                return QCUnifyReturnValue.Warn("存在已派单的隐患治理记录，请求重新勾选记录");

            Date planBeginTm = DateUtil.getNowDate();//计划开始时间默认从当前开始
            Date planEndTm = endDate;//计划截止时间为隐患治理的整改时限

            //新增一个隐患任务
            EhsTaskInfo taskInfo = new EhsTaskInfo();
            taskInfo.setTaskid(IdentifierUtil.randomUUID());
            taskInfo.setOrgcode(ens.get(0x0).getOrgcode());
            taskInfo.setTasktitle(dto.getTitle());//任务标题
            taskInfo.setTaskcontent(dto.getDescription());//任务内容
            taskInfo.setCatname(EhsTaskCategoryTypeEnum.HIDDEN_DANGER_CONTROL.getName());
            taskInfo.setTasktype(EhsTaskCategoryTypeEnum.HIDDEN_DANGER_CONTROL);
            //任务分组设置为按隐患分组
            taskInfo.setGroupobjtype(EhsTaskGroupObjectTypeEnum.TROUBLE);
            taskInfo.setObjtype(EhsTaskDestObjectTypeEnum.SECOND_TYPE_HAZARD);
            taskInfo.setNotnull(true);
            taskInfo.setNeedchecktable(false);
            taskInfo.setNeedsignin(false);
            taskInfo.setNeedconfirm(false);
            taskInfo.setInuserid(userInfo.getId());
            taskInfo.setInusername(userInfo.getName());
            taskInfo.setIntm(DateUtil.getNowDate());
            taskInfo.setPlanbegintm(planBeginTm);
            taskInfo.setPlanendtm(planEndTm);
            taskInfo.setPlanfrequencytype(TimeRangeLengthEnum.CUSTOM);//计划执行周期类型：自定义
            taskInfo.setPlanfrequencycount(0x1);//每周内计划执行次数：1次
            taskInfo.setPlantotalcount(0x1);
            taskInfo.setHasdispatch(true);
            taskInfo.setHasfinish(false);
            taskInfo.setHasend(false);
            taskInfo.setExeccount(0x0);
            taskInfo.setExecidentifycount(0x0);
            taskInfo.setExectroublecount(0x0);
            if (taskInfoRepository.insert(taskInfo) < 0x1) {
                return QCUnifyReturnValue.Warn("新增隐患任务失败。");
            }

            //新增任务分组，一个隐患为一个分组
            for (EhsTroubleCorrect en : ens) {
                //获取指定隐患信息
                EhsHazardInfoDto hazardInfoDto = hazardInfoService.get(en.getHazardid());

                EhsTaskGroup group = new EhsTaskGroup();
                group.setGroupid(IdentifierUtil.randomUUID());
                group.setGroupname(en.getTitle());//任务分组名称：隐患/问题标题
                group.setOdr(1999);
                group.setTaskid(taskInfo.getTaskid());
                group.setUnitid(en.getUnitid());
                group.setUnitname(en.getUnitname());
                group.setHazardid(en.getHazardid());
                group.setHazardname(hazardInfoDto.getHazardname());
                //责任部门：隐患的整改责任部门
                group.setResdeptid(en.getResdeptid());
                group.setResdeptname(en.getResdeptname());
                group.setResuserid1(en.getResuserid());
                group.setResusername1(en.getResusername());
                group.setHasfinish(false);
                group.setHasend(false);
                group.setExeccount(0x0);
                group.setExecidentifycount(0x0);
                group.setExectroublecount(0x0);
                if (taskGroupRepository.insert(group) < 0x1) {
                    return QCUnifyReturnValue.Warn("新增隐患任务分组失败");
                }

                //新增任务项：对指定任务进行派单
                EhsTaskItem item = new EhsTaskItem();
                item.setItemid(IdentifierUtil.randomUUID());
                item.setTaskid(taskInfo.getTaskid());
                item.setItemname(en.getTitle());
                item.setGroupid(group.getGroupid());
                item.setOrgcode(taskInfo.getOrgcode());
                item.setCatname(taskInfo.getCatname());
                item.setTasktype(taskInfo.getTasktype());
                item.setPlantmstr(DateUtil.getDateString(planBeginTm) + "~" + DateUtil.getDateString(planEndTm));
                item.setPlanbegintm(planBeginTm);
                item.setPlanendtm(planEndTm);
                item.setPlanfrequencytype(taskInfo.getPlanfrequencytype());
                item.setPlanfrequencycount(taskInfo.getPlanfrequencycount());
                item.setUnitid(group.getUnitid());
                item.setUnitname(group.getUnitname());
                item.setFacilityid(group.getFacilityid());
                item.setFacilityname(group.getFacilityname());
                item.setHazardid(group.getHazardid());
                item.setHazardname(group.getHazardname());
                //责任部门、参与组员1和参与组员2直接使用任务分组表中的对应属性值；
                item.setResdeptid(group.getResdeptid());
                item.setResdeptname(group.getResdeptname());
                item.setResuserid1(group.getResuserid1());
                item.setResusername1(group.getResusername1());
                item.setResuserid2(group.getResuserid2());
                item.setResusername2(group.getResusername2());
                item.setHasfinish(false);
                item.setHasend(false);
                item.setExeccount(0x0);
                item.setExecidentifycount(0X0);
                item.setExectroublecount(0x0);
                if (taskItemRepository.insert(item) < 0x1) {
                    return QCUnifyReturnValue.Warn("隐患任务派单失败。");
                }
            }

            //修改隐患治理信息
            LambdaUpdateWrapper<EhsTroubleCorrect> wrapper = new LambdaUpdateWrapper<>();
            wrapper.in(EhsTroubleCorrect::getCorrectid, dto.getIds())
                    .set(EhsTroubleCorrect::getHasdispatch, true)
                    .set(EhsTroubleCorrect::getReqendtm, endDate)
                    .set(EhsTroubleCorrect::getReqdescription, dto.getDescription());
            repository.update(null, wrapper);
        }

        return QCUnifyReturnValue.Success();
    }

    /**
     * 派单
     * <p>
     * 要求隐患未派单，已派单的不再重复操作
     * 隐患派单后，新增一个任务，新增一个任务分组（隐患为1个分组），新增任务项
     * @param dto 派单DTO
     * @return 成功返回null，失败返回错误或提示信息
     * @author QuCHeng Tech
     * @since 2024/11/19
     */
    public String dispatch(EhsTroubleCorrectDispatchDto dto, UacUserInfoDto userInfo) throws QCPromptException {
        //1.DTO有效性验证
        if (dto == null)
            return QCUnifyReturnValue.Warn("派单信息不能为空");
        if (StringUtils.isBlank(dto.getId()))
            return QCUnifyReturnValue.Warn("隐患治理ID不能为空");
        if (StringUtils.isBlank(dto.getEndtm()))
            return QCUnifyReturnValue.Warn("整改时限不能为空");
        if (dto.getDeptid() == null)
            return QCUnifyReturnValue.Warn("整改责任部门ID不能为空");
        if (dto.getUserid() == null)
            return QCUnifyReturnValue.Warn("整改负责人ID不能为空");

        EhsTroubleCorrect en = repository.selectById(dto.getId());
        if (Objects.isNull(en))
            return QCUnifyReturnValue.Warn("隐患治理信息不存在");

        if (en.getHasdispatch() != null && en.getHasdispatch())
            return QCUnifyReturnValue.Warn("隐患已派单整改，不再重复操作。");

        //获取指定隐患信息
        EhsHazardInfoDto hazardInfoDto = hazardInfoService.get(en.getHazardid());

        //2.修改隐患治理信息
        en.setHasdispatch(true);
        en.setReqdescription(dto.getDescription());
        en.setReqendtm(DateUtil.parseDate(dto.getEndtm()));
        en.setResdeptid(dto.getDeptid());
        en.setResdeptname(dto.getDeptname());
        en.setResuserid(dto.getUserid());
        en.setResusername(dto.getUsername());
        en.setResuserphone(dto.getUserphone());
        repository.updateById(en);

        //新增一个隐患任务
        Date planBeginTm = DateUtil.getNowDate();//计划开始时间默认从当前开始
        Date planEndTm = en.getReqendtm();//计划截止时间为隐患治理的整改时限
        EhsTaskInfo taskInfo = new EhsTaskInfo();
        taskInfo.setTaskid(IdentifierUtil.randomUUID());
        taskInfo.setOrgcode(en.getOrgcode());
        taskInfo.setTasktitle(en.getTitle());//任务标题：隐患/问题标题
        taskInfo.setTaskcontent(en.getDescription());//任务内容：隐患/问题描述
        taskInfo.setTaskattachment(en.getAttachment());//任务附件：隐患/问题的附件
        taskInfo.setCatname(EhsTaskCategoryTypeEnum.HIDDEN_DANGER_CONTROL.getName());
        taskInfo.setTasktype(EhsTaskCategoryTypeEnum.HIDDEN_DANGER_CONTROL);
        //任务分组设置为按隐患分组
        taskInfo.setGroupobjtype(EhsTaskGroupObjectTypeEnum.TROUBLE);
        taskInfo.setObjtype(EhsTaskDestObjectTypeEnum.SECOND_TYPE_HAZARD);
        taskInfo.setNotnull(true);
        taskInfo.setNeedchecktable(false);
        taskInfo.setNeedsignin(false);
        taskInfo.setNeedconfirm(false);
        taskInfo.setInuserid(userInfo.getId());
        taskInfo.setInusername(userInfo.getName());
        taskInfo.setIntm(DateUtil.getNowDate());
        taskInfo.setPlanbegintm(planBeginTm);
        taskInfo.setPlanendtm(planEndTm);
        taskInfo.setPlanfrequencytype(TimeRangeLengthEnum.CUSTOM);//计划执行周期类型：自定义
        taskInfo.setPlanfrequencycount(0x1);//每周内计划执行次数：1次
        taskInfo.setPlantotalcount(0x1);
        taskInfo.setHasdispatch(true);
        taskInfo.setHasfinish(false);
        taskInfo.setHasend(false);
        taskInfo.setExeccount(0x0);
        taskInfo.setExecidentifycount(0x0);
        taskInfo.setExectroublecount(0x0);
        if (taskInfoRepository.insert(taskInfo) < 0x1) {
            return QCUnifyReturnValue.Warn("新增隐患任务失败。");
        }

        //新增任务的分组
        EhsTaskGroup group = new EhsTaskGroup();
        group.setGroupid(IdentifierUtil.randomUUID());
        group.setGroupname(en.getTitle());//任务分组名称：隐患/问题标题
        group.setOdr(1999);
        group.setTaskid(taskInfo.getTaskid());
        group.setUnitid(en.getUnitid());
        group.setUnitname(en.getUnitname());
        group.setHazardid(en.getHazardid());
        group.setHazardname(hazardInfoDto.getHazardname());
        //责任部门：隐患的整改责任部门
        group.setResdeptid(en.getResdeptid());
        group.setResdeptname(en.getResdeptname());
        group.setResuserid1(en.getResuserid());
        group.setResusername1(en.getResusername());
        group.setHasfinish(false);
        group.setHasend(false);
        group.setExeccount(0x0);
        group.setExecidentifycount(0x0);
        group.setExectroublecount(0x0);
        if (taskGroupRepository.insert(group) < 0x1) {
            return QCUnifyReturnValue.Warn("新增隐患任务分组失败");
        }

        //新增任务项：对指定任务进行派单
        EhsTaskItem item = new EhsTaskItem();
        item.setItemid(IdentifierUtil.randomUUID());
        item.setTaskid(taskInfo.getTaskid());
        item.setItemname(taskInfo.getTasktitle());
        item.setGroupid(group.getGroupid());
        item.setOrgcode(taskInfo.getOrgcode());
        item.setCatname(taskInfo.getCatname());
        item.setTasktype(taskInfo.getTasktype());
        item.setPlantmstr(DateUtil.getDateString(planBeginTm) + "~" + DateUtil.getDateString(planEndTm));
        item.setPlanbegintm(planBeginTm);
        item.setPlanendtm(planEndTm);
        item.setPlanfrequencytype(taskInfo.getPlanfrequencytype());
        item.setPlanfrequencycount(taskInfo.getPlanfrequencycount());
        item.setUnitid(group.getUnitid());
        item.setUnitname(group.getUnitname());
        item.setFacilityid(group.getFacilityid());
        item.setFacilityname(group.getFacilityname());
        item.setHazardid(group.getHazardid());
        item.setHazardname(group.getHazardname());
        //责任部门、参与组员1和参与组员2直接使用任务分组表中的对应属性值；
        item.setResdeptid(group.getResdeptid());
        item.setResdeptname(group.getResdeptname());
        item.setResuserid1(group.getResuserid1());
        item.setResusername1(group.getResusername1());
        item.setResuserid2(group.getResuserid2());
        item.setResusername2(group.getResusername2());
        item.setHasfinish(false);
        item.setHasend(false);
        item.setExeccount(0x0);
        item.setExecidentifycount(0X0);
        item.setExectroublecount(0x0);
        if (taskItemRepository.insert(item) < 0x1) {
            return QCUnifyReturnValue.Warn("隐患任务派单失败。");
        }

        return QCUnifyReturnValue.Success();
    }

    /**
     * 整改
     * @param dto 整改完成填写DTO
     * @return 成功返回null，失败返回错误或提示信息
     * @author QuCHeng Tech
     * @since 2024/11/7
     */
    public String correct(EhsTroubleCorrectCompleteDto dto) throws QCPromptException {
        //1.DTO有效性验证
        if (dto == null) return QCUnifyReturnValue.Warn("整改信息不能为空");
        if (StringUtils.isBlank(dto.getId())) return QCUnifyReturnValue.Warn("隐患治理ID不能为空");
        EhsTroubleCorrect en = repository.selectById(dto.getId());
        if (Objects.isNull(en))
            return QCUnifyReturnValue.Warn("隐患治理信息不存在");

        if (StringUtils.isBlank(dto.getUsername())) return QCUnifyReturnValue.Warn("实际整改人员不能为空");
        if (StringUtils.isBlank(dto.getTm())) return QCUnifyReturnValue.Warn("实际整改时间不能为空");
        //如果整改完成设置为true，判断整改完成时间
        if (dto.isHascorrect()) {
            en.setHascorrect(true);

            if (StringUtils.isBlank(dto.getEndtm()))
                return QCUnifyReturnValue.Warn("整改完成时间不能为空");

            //判断整改完成时间是否有效，不能大于当前时间
            try {
                Date endTime = DateUtil.parseDate(dto.getEndtm());
                if (endTime.after(DateUtil.getNowDate()))
                    throw new QCPromptException("整改完成时间不能大于当前时间");

                en.setCorrectendtm(endTime);
            } catch (Exception e) {
                // 时间转换错误，抛出自定义异常
                throw new QCPromptException("整改完成时间转换错误");
            }
        }

        //2.修改隐患治理信息
        en.setCorrectusername(dto.getUsername());
        en.setCorrecttm(dto.getTm());
        en.setCorrectdescription(dto.getDescription());
        en.setCorrectattachment(dto.getAttachment());
        en.setCorrectsign(dto.getSign());

        repository.updateById(en);

        return QCUnifyReturnValue.Success();
    }

    /**
     * 验收
     * @param dto 验收DTO
     * @return 成功返回null，失败返回错误或提示信息
     * @author QuCHeng Tech
     * @since 2024/11/8
     */
    public String check(EhsTroubleCorrectCheckDto dto) {
        //1.DTO有效性验证
        if (dto == null) return QCUnifyReturnValue.Warn("整改信息不能为空");
        if (StringUtils.isBlank(dto.getId())) return QCUnifyReturnValue.Warn("隐患治理ID不能为空");
        if (StringUtils.isBlank(dto.getUsername())) return QCUnifyReturnValue.Warn("验收人员不能为空");
        if (StringUtils.isBlank(dto.getEndtm())) return QCUnifyReturnValue.Warn("验收时间不能为空");

        EhsTroubleCorrect en = repository.selectById(dto.getId());
        if (Objects.isNull(en)) return QCUnifyReturnValue.Warn("隐患治理信息不存在");

        //2.修改隐患治理信息
        en.setHascheck(dto.isHascheck());
        en.setCheckusername(dto.getUsername());
        en.setChecktm(DateUtil.parseDate(dto.getEndtm()));
        en.setCheckdescription(dto.getDescription());
        en.setChecksign(dto.getSign());
        en.setCheckattachment(dto.getAttachment());
        repository.updateById(en);
        return QCUnifyReturnValue.Success();
    }

    /**
     * 获取指定危险源的隐患治理记录
     * @param hazardId 危险源ID
     * @return List<EhsTroubleCorrectInfoDto>
     * @author QuCheng Tech
     * @since 2024/11/11
     */
    public List<EhsTroubleCorrectInfoDto> getByHazard(String hazardId) {
        LambdaQueryWrapper<EhsTroubleCorrect> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EhsTroubleCorrect::getHazardid, hazardId)
                .orderByDesc(EhsTroubleCorrect::getTm);
        List<EhsTroubleCorrect> ens = repository.selectList(wrapper);
        if (CollectionUtils.isNotEmpty(ens)) {
            return EhsTroubleCorrectMapper.MAPPER.toDtoList(ens);
        }
        return null;
    }

    /**
     * 获取指定隐患治理
     * @param troubleCorrectId 隐患治理ID
     * @return EhsTroubleCorrectInfoDto
     * @author QuCheng Tech
     * @since 2024/11/22
     */
    public EhsTroubleCorrectInfoDto get(String troubleCorrectId) {

        EhsTroubleCorrect en = repository.selectById(troubleCorrectId);
        if (Objects.nonNull(en)) {
            return EhsTroubleCorrectMapper.MAPPER.toDto(en);
        }
        return null;
    }

    /**
     * 获取指定隐患治理Entity
     * @param troubleCorrectId 隐患治理ID
     * @return EhsTroubleCorrect
     * @author QuCheng Tech
     * @since 2025/1/18
     */
    public EhsTroubleCorrect getEntity(String troubleCorrectId) {
        if (StringUtils.isNotBlank(troubleCorrectId))
            return repository.selectById(troubleCorrectId);

        return null;
    }

    /**
     * 新增隐患治理信息
     * @param dto 新增DTO
     * @return 成功返回null，失败返回错误或提示信息
     * @author QuCheng Tech
     * @since 2024/11/7
     */
    public String add(EhsTroubleCorrectInfoDto dto) {
        //DTO有效性验证
        if (dto == null) return QCUnifyReturnValue.Warn("新增对象不能为空");
        if (StringUtils.isBlank(dto.getHazardid())) return QCUnifyReturnValue.Warn("隐患ID不能为空");
        if (StringUtils.isBlank(dto.getOrgcode())) return QCUnifyReturnValue.Warn("所属组织代码不能为空");
        if (StringUtils.isBlank(dto.getTm())) return QCUnifyReturnValue.Warn("发现时间不能为空");
        if (StringUtils.isBlank(dto.getUnitid())) return QCUnifyReturnValue.Warn("单元ID不能为空");
        if (StringUtils.isBlank(dto.getUnit())) return QCUnifyReturnValue.Warn("单元名称不能为空");
        if (StringUtils.isBlank(dto.getTitle())) return QCUnifyReturnValue.Warn("标题不能为空");

        EhsTroubleCorrect en = EhsTroubleCorrectMapper.MAPPER.dtoToEntity(dto);
        if (StringUtils.isBlank(en.getCorrectid())) en.setCorrectid(IdentifierUtil.randomUUID());
        en.setIntm(DateUtil.getNowDate());

        if (repository.insert(en) < 0x1) {
            return QCUnifyReturnValue.Warn("保存隐患治理信息失败");
        }
        return QCUnifyReturnValue.Success();
    }

    /**
     * 删除隐患治理信息
     * @param troubleCorrectId 隐患治理ID
     * @return 成功返回null，失败返回错误或提示信息
     * @author QuCheng Tech
     * @since 2024/11/8
     */
    public String delete(String troubleCorrectId) {
        repository.deleteById(troubleCorrectId);
        return QCUnifyReturnValue.Success();
    }

    /**
     * 获取指定隐患的最新隐患治理记录
     * @param hazardId 隐患ID
     * @return EhsTroubleCorrectInfoDto
     * @author QuCHeng Tech
     * @since 2024/11/7
     */
    public EhsTroubleCorrectInfoDto getByHazardId(String hazardId) {
        LambdaQueryWrapper<EhsTroubleCorrect> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EhsTroubleCorrect::getHazardid, hazardId)
                .orderByDesc(EhsTroubleCorrect::getIntm);
        EhsTroubleCorrect en = repository.selectOne(wrapper);
        if (Objects.nonNull(en)) {
            return EhsTroubleCorrectMapper.MAPPER.toDto(en);
        }
        return null;
    }

    /**
     * 获取指定隐患指定发现时间的隐患治理记录
     * @param hazardId 隐患ID
     * @param tm       发现时间
     * @return EhsTroubleCorrectInfoDto
     * @author QuCHeng Tech
     * @since 2024/11/8
     */
    public EhsTroubleCorrectInfoDto getByHazardIdAnDTm(String hazardId, Date tm) {
        LambdaQueryWrapper<EhsTroubleCorrect> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EhsTroubleCorrect::getHazardid, hazardId)
                .eq(EhsTroubleCorrect::getTm, tm);
        EhsTroubleCorrect en = repository.selectOne(wrapper);
        if (Objects.nonNull(en)) {
            return EhsTroubleCorrectMapper.MAPPER.toDto(en);
        }
        return null;
    }

    /**
     * 更新隐患治理记录的风险等级评价
     * @param ids 治理ID集合
     * @return 成功返回null，失败返回错误或提示信息
     * @author QuCheng Tech
     * @since 2024/12/2
     */
    public String updateRiskLevel(List<String> ids, Integer risklevel) {
        LambdaUpdateWrapper<EhsTroubleCorrect> wrapper = new LambdaUpdateWrapper<>();
        wrapper.in(EhsTroubleCorrect::getCorrectid, ids)
                .set(EhsTroubleCorrect::getRisklevel, risklevel);

        repository.update(null, wrapper);
        return QCUnifyReturnValue.Success();
    }

    /**
     * 查询指定组织中指定时间段内的隐患治理集合
     * @param orgCode   组织机构代码
     * @param beginTime 起始时间
     * @param endTime   截止时间
     * @return java.util.List<qc.module.ehs.entity.EhsTroubleCorrect>
     * @author QuCheng Tech
     * @since 2024/12/17
     */
    public List<EhsTroubleCorrect> getOrgAllTroubleCorrects(String orgCode, Date beginTime, Date endTime) throws QCPromptException {
        if (StringUtils.isBlank(orgCode))
            throw new QCPromptException("查询隐患治理的组织机构代码不能为空");

        LambdaQueryWrapper<EhsTroubleCorrect> wrapper = new LambdaQueryWrapper<>();
        //组织机构代码，必须有，判断相等
        wrapper.eq(EhsTroubleCorrect::getOrgcode, orgCode);
        //根据隐患治理表中的发现时间进行统计
        wrapper.ge(EhsTroubleCorrect::getTm, beginTime);
        wrapper.le(EhsTroubleCorrect::getTm, endTime);

        return repository.selectList(wrapper);
    }

    /***
     * 更新指定的隐患治理对应的报告ID
     *
     * @param troubleCorrectId 隐患治理ID
     * @param fileId 报告文件ID
     * @return java.lang.String
     * @author QuCheng Tech
     * @since 2025/3/6
     */
    public String updateReport(String troubleCorrectId, int fileId) {
        if (StringUtils.isBlank(troubleCorrectId))
            return QCUnifyReturnValue.Warn("隐患治理ID不能为空");
        if (fileId < 0x1)
            return QCUnifyReturnValue.Warn("报告文件ID无效");

        LambdaUpdateWrapper<EhsTroubleCorrect> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(EhsTroubleCorrect::getCorrectid, troubleCorrectId)
                .set(EhsTroubleCorrect::getRptid, fileId);

        if (repository.update(null, wrapper) != 0x1)
            return QCUnifyReturnValue.Warn("更新隐患治理报告文件ID失败");

        return QCUnifyReturnValue.Success();
    }

    /**
     * 查询指定单元的隐患治理信息
     *
     * @param unitid    单元id
     * @param beginDate 起始时间
     * @param endDate   截止时间
     * @return List<EhsTroubleCorrect>
     * @since 2025/6/9
     */
    public List<EhsTroubleCorrect> queryUnitTroubleCorrects(String unitid, Date beginDate, Date endDate) throws QCPromptException {
        if (StringUtils.isBlank(unitid))
            throw new QCPromptException("查询隐患治理的单元ID不能为空");

        LambdaQueryWrapper<EhsTroubleCorrect> wrapper = new LambdaQueryWrapper<>();
        //单元ID，必须有，判断相等
        wrapper.eq(EhsTroubleCorrect::getUnitid, unitid)
                .ge(EhsTroubleCorrect::getTm, beginDate)
                .le(EhsTroubleCorrect::getTm, endDate)
                .orderByDesc(EhsTroubleCorrect::getTm); //最新发现的隐患在前

        return repository.selectList(wrapper);
    }
}
